﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
using BusinessLogic.Interfaces;
using Domain.Entities;
using Ninject;


namespace BisinessLogic
{
  public   class PrimaryMembershipProvider :MembershipProvider
    {
      [Inject]
      public IUsersRepository UsersRepository { get; set; }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public MembershipCreateStatus CreateUser(string login, string password, string email, string firstName,
           string lastName, string middleName,int roleId)
        {
            if (UsersRepository.GetUserLoginByEmail(email) != "")
            {
                return MembershipCreateStatus.DuplicateEmail;
            }
            MembershipUser user = UsersRepository.GetMembershipUserByLogin(login);
            if (user != null)
            {
                return MembershipCreateStatus.DuplicateUserName;
            }
            password = GetHashString(password);
            UsersRepository.CreateUser(login, password, email, firstName, lastName, middleName, roleId);
            return MembershipCreateStatus.Success;
        }


        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            return UsersRepository.GetMembershipUserByLogin(username);
        }


      public override bool ValidateUser(string username, string password)
        {
            string hashPassword = GetHashString(password);
            username = username.ToLower();
            return UsersRepository.ValidateUser(username, hashPassword);
        }

        string GetHashString(string s)
        {
            //переводим строку в байт-массим  
            byte[] bytes = Encoding.Unicode.GetBytes(s);

            //создаем объект для получения средст шифрования  
            MD5CryptoServiceProvider CSP =
                new MD5CryptoServiceProvider();

            //вычисляем хеш-представление в байтах  
            byte[] byteHash = CSP.ComputeHash(bytes);

            string hash = string.Empty;

            //формируем одну цельную строку из массива  
            foreach (byte b in byteHash)
                hash += string.Format("{0:x2}", b);

            return hash;
        }

        public MembershipCreateStatus UpdateUser(User user)
        {
            if (user.Id == 0)
            {
           
              return  CreateUser(user.Login, user.Password, user.Email, user.FirstName, user.LastName, user.MiddleName,
                    user.RoleId);
            }
            if (UsersRepository.GetUsers().Count(u => u.Email==user.Email && u.Id!=user.Id)>0)
            {
                return MembershipCreateStatus.DuplicateEmail;
            }
            if (UsersRepository.GetUsers().Count(u=>u.Login.ToLower()==user.Login.ToLower()&& u.Id!=user.Id)>0)
            {
                return MembershipCreateStatus.DuplicateUserName;
            }
            // =>  Если логин  и эмейл не заняты, позволим поменять данные.
            if (UsersRepository.GetUserById(user.Id).Password != user.Password)
            {
                // пользователь сменил пароль
               user.Password = GetHashString(user.Password);  
            }
            UsersRepository.SaveUser(user);
            return MembershipCreateStatus.Success;
        }







        #region NotImplemented

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }


        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

       

        #endregion
    }
}
